<?php
namespace app\service;

use app\model\{
    LearningRecord, 
    ScoreDetail, 
    TeachingPlanElement, 
    TeachingPlan, 
    CourseOutline, 
    ChatSession, 
    ChatMessage, 
    User, 
    AiRole
};
use think\facade\{Log, Db};
use Exception;

class LearningService
{
    protected $chatService;
    protected $aiChatService;
    protected $aiEvaluationService;
    protected $topicCompletionService;

    public function __construct()
    {
        $this->chatService = new ChatService();
        $this->aiChatService = new AiChatService();
        $this->aiEvaluationService = new AiEvaluationService();
        $this->topicCompletionService = new TopicCompletionService();
    }

    /**
     * 处理学习对话
     */
    public function handleLearningChat(User $user, array $params): array
    {
        $content = $params['content'] ?? '';
        $elementId = $params['element_id'] ?? 0;
        $sessionId = $params['session_id'] ?? 0;
        $messageId = $params['message_id'] ?? 0;
        $teachingPlanId = $params['teaching_plan_id'] ?? 0;
        $courseId = $params['course_id'] ?? 0;
        $learningMode = $params['learning_mode'] ?? 'training';
        $aiRoleId = $params['ai_role_id'] ?? 0;

        if (!$elementId) {
            throw new Exception('element_id不能为空');
        }

        // 获取教案元素
        $element = TeachingPlanElement::find($elementId);
        if (!$element) {
            throw new Exception('教案元素不存在');
        }

        // 获取或创建学习记录
        $learningRecord = $this->getOrCreateLearningRecord($user, $element, $courseId, $teachingPlanId);

        // 获取或创建会话
        $session = $this->getOrCreateSession($user, $sessionId, $learningRecord);

        // 选择AI角色
        $aiRole = $this->selectAiRole($user, $aiRoleId, $courseId, $element->plan_id);

        // 处理不同类型的教案元素
        if ($element->type === TeachingPlanElement::TYPE_QUESTION && $content) {
            // 提问类元素：评估用户回答（在handleQuestionElement中会保存用户消息）
            return $this->handleQuestionElement($user, $session, $element, $content, $learningMode, $learningRecord, $aiRole);
        } else {
            // 讲解类元素：提供教学内容
            if ($content) {
                $this->chatService->sendMessage($session->id, $user, $content);
            }
            return $this->handleLectureElement($user, $session, $element, $learningMode, $learningRecord, $aiRole);
        }
    }

    /**
     * 处理提问类元素
     */
    protected function handleQuestionElement(User $user, ChatSession $session, TeachingPlanElement $element, string $content, string $learningMode, LearningRecord $learningRecord, ?AiRole $aiRole): array
    {
        // 保存用户消息并获取消息ID
        $userMessage = $this->chatService->sendMessage($session->id, $user, $content);
        
        // 获取历史消息进行评估
        $history = $this->chatService->getSessionHistory($session->id);
        
        // AI评估用户回答
        $evaluation = $this->aiEvaluationService->evaluateUserAnswer(
            $history,
            $element->answer,
            [
                'total' => $element->score,
                'passing' => $element->passing_score
            ]
        );

        // 记录得分（传递用户消息ID）
        $scoreDetail = $this->recordScore($user, $learningRecord, $element, $evaluation, $content, $userMessage->id);

        // 判断是否继续下一个元素
        $shouldContinue = $this->shouldContinueToNext($evaluation['passed'], $learningMode);
        $nextElement = $shouldContinue ? $this->getNextElement($element) : $element;

        // 更新学习进度
        if ($shouldContinue && $nextElement && $nextElement->id !== $element->id) {
            $this->updateLearningProgress($learningRecord, $nextElement->id);
        }

        // 创建AI回复消息
        $aiMessage = $this->createAiResponseMessage($user, $session->id, $element, $aiRole, $learningMode, $evaluation);

        return [
            'session_id' => $session->id,
            'message_id' => $aiMessage->id,
            'user_message_id' => $userMessage->id, // 新增用户消息ID
            'next_element_id' => $nextElement ? $nextElement->id : null,
            'current_score' => $evaluation['score'],
            'is_passed' => $evaluation['passed'],
            'should_continue' => $shouldContinue,
            'element_type' => $element->type,
            'learning_progress' => $this->calculateProgress($learningRecord),
            'evaluation_result' => $evaluation,
            'ai_role' => $aiRole ? [
                'id' => $aiRole->id,
                'name' => $aiRole->name,
                'description' => $aiRole->description
            ] : null
        ];
    }

    /**
     * 处理讲解类元素
     */
    protected function handleLectureElement(User $user, ChatSession $session, TeachingPlanElement $element, string $learningMode, LearningRecord $learningRecord, ?AiRole $aiRole): array
    {
        // 检查话题完成度（如果用户有回复内容）
        $shouldContinue = false;
        $history = $this->chatService->getSessionHistory($session->id);
        
        if (count($history) > 1) { // 有对话历史
            $completion = $this->topicCompletionService->checkCompletion($session, $user);
            $shouldContinue = $completion['next'] === 1;
        }

        $nextElement = $shouldContinue ? $this->getNextElement($element) : $element;

        // 更新学习进度
        if ($shouldContinue && $nextElement && $nextElement->id !== $element->id) {
            $this->updateLearningProgress($learningRecord, $nextElement->id);
        }

        // 创建AI回复消息
        $aiMessage = $this->createAiResponseMessage($user, $session->id, $element, $aiRole, $learningMode);

        return [
            'session_id' => $session->id,
            'message_id' => $aiMessage->id,
            'next_element_id' => $nextElement ? $nextElement->id : null,
            'current_score' => null,
            'is_passed' => null,
            'should_continue' => $shouldContinue,
            'element_type' => $element->type,
            'learning_progress' => $this->calculateProgress($learningRecord),
            'evaluation_result' => null,
            'ai_role' => $aiRole ? [
                'id' => $aiRole->id,
                'name' => $aiRole->name,
                'description' => $aiRole->description
            ] : null
        ];
    }

    /**
     * 初始化学习会话
     */
    public function initLearningSession(User $user, array $params): array
    {
        $courseId = $params['course_id'] ?? null;
        $teachingPlanId = $params['teaching_plan_id'] ?? null;
        $elementId = $params['element_id'] ?? null;
        $learningMode = $params['learning_mode'] ?? 'training';

        if (!$courseId && !$teachingPlanId) {
            throw new Exception('请提供课程ID或教案ID');
        }

        // 查找或创建学习记录
        $existingRecord = $this->findExistingLearningRecord($user, $courseId, $teachingPlanId);
        
        if ($existingRecord) {
            // 恢复现有学习
            $learningRecord = LearningRecord::find($existingRecord['learning_records_id']);
            $session = ChatSession::find($existingRecord['session_id']);
            
            return [
                'session_id' => $session->id,
                'learning_record_id' => $learningRecord->id,
                'first_element_id' => $learningRecord->current_element_id ?: $this->getFirstElementId($learningRecord),
                'total_elements' => $this->getTotalElements($learningRecord),
                'teaching_plan' => $this->getTeachingPlanInfo($learningRecord->current_plan_id),
                'course' => $courseId ? $this->getCourseInfo($courseId) : null
            ];
        } else {
            // 创建新的学习会话
            return $this->createNewLearningSession($user, $courseId, $teachingPlanId, $elementId, $learningMode);
        }
    }

    /**
     * 获取学习进度
     */
    public function getProgress(User $user, array $params): array
    {
        $courseId = $params['course_id'] ?? null;
        $teachingPlanId = $params['teaching_plan_id'] ?? null;
        $sessionId = $params['session_id'] ?? null;

        $query = LearningRecord::where('user_id', $user->id);
        
        if ($sessionId) {
            $session = ChatSession::find($sessionId);
            if ($session && $session->learning_records_id) {
                $query->where('id', $session->learning_records_id);
            }
        } elseif ($courseId) {
            $query->where('course_id', $courseId);
        } elseif ($teachingPlanId) {
            $query->where('teaching_plan_id', $teachingPlanId);
        } else {
            throw new Exception('请提供课程ID、教案ID或会话ID');
        }

        $record = $query->find();
        if (!$record) {
            throw new Exception('学习记录不存在');
        }

        return [
            'learning_record' => [
                'id' => $record->id,
                'course_id' => $record->course_id,
                'teaching_plan_id' => $record->teaching_plan_id,
                'current_element_id' => $record->current_element_id,
                'progress_rate' => $record->progress_rate,
                'achieved_score' => $record->achieved_score,
                'status' => $record->status,
                'last_study_at' => date('Y-m-d H:i:s', $record->last_study_at)
            ],
            'progress_details' => $this->calculateProgress($record),
            'recent_scores' => $this->getRecentScores($record->id)
        ];
    }

    /**
     * 获取学习历史
     */
    public function getHistory(User $user, array $params): array
    {
        $page = $params['page'] ?? 1;
        $pageSize = $params['page_size'] ?? 10;
        $status = $params['status'] ?? null;

        $query = LearningRecord::where('user_id', $user->id);
        
        if ($status !== null) {
            $query->where('status', $status);
        }

        $records = $query->with(['course', 'teachingPlan'])
            ->order('created_at', 'desc')
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ]);

        $formattedRecords = [];
        foreach ($records->items() as $record) {
            $formattedRecords[] = [
                'id' => $record->id,
                'course_title' => $record->course ? $record->course->title : null,
                'teaching_plan_title' => $record->teachingPlan ? $record->teachingPlan->title : null,
                'progress_rate' => $record->progress_rate,
                'achieved_score' => $record->achieved_score,
                'status' => $record->status,
                'status_text' => $this->getStatusText($record->status),
                'last_study_at' => date('Y-m-d H:i:s', $record->last_study_at),
                'created_at' => date('Y-m-d H:i:s', $record->created_at)
            ];
        }

        return [
            'total' => $records->total(),
            'current_page' => $records->currentPage(),
            'last_page' => $records->lastPage(),
            'records' => $formattedRecords
        ];
    }

    /**
     * 获取或创建学习记录
     */
    protected function getOrCreateLearningRecord(User $user, TeachingPlanElement $element, ?int $courseId, ?int $teachingPlanId): LearningRecord
    {
        $planId = $teachingPlanId ?: $element->plan_id;
        
        $record = LearningRecord::where('user_id', $user->id)
            ->where(function($query) use ($courseId, $planId) {
                if ($courseId) {
                    $query->where('course_id', $courseId);
                } else {
                    $query->where('teaching_plan_id', $planId);
                }
            })
            ->where('status', LearningRecord::STATUS_IN_PROGRESS)
            ->find();

        if (!$record) {
            $record = new LearningRecord();
            $record->user_id = $user->id;
            $record->course_id = $courseId;
            $record->teaching_plan_id = $planId;
            $record->current_plan_id = $planId;
            $record->current_element_id = $element->id;
            $record->learning_type = LearningRecord::TYPE_REVIEW;
            $record->status = LearningRecord::STATUS_IN_PROGRESS;
            $record->last_study_at = time();
            $record->save();
        }

        return $record;
    }

    /**
     * 获取或创建会话
     */
    protected function getOrCreateSession(User $user, ?int $sessionId, LearningRecord $learningRecord): ChatSession
    {
        if ($sessionId) {
            $session = ChatSession::where('id', $sessionId)
                ->where('user_id', $user->id)
                ->find();
            if ($session) {
                return $session;
            }
        }

        // 查找现有学习会话
        $session = ChatSession::where('user_id', $user->id)
            ->where('learning_records_id', $learningRecord->id)
            ->find();

        if (!$session) {
            $session = $this->chatService->createSession($user, [
                'title' => '智能学习会话',
                'session_type' => 4, // 学习会话
                'learning_records_id' => $learningRecord->id
            ]);
        }

        return $session;
    }

    /**
     * 选择AI角色
     */
    protected function selectAiRole(User $user, ?int $aiRoleId, ?int $courseId, ?int $planId): ?AiRole
    {
        // 优先级：接口指定 > 课程指定 > 教案指定 > 用户默认
        if ($aiRoleId) {
            return AiRole::find($aiRoleId);
        }
        
        if ($courseId) {
            $course = CourseOutline::find($courseId);
            if ($course && $course->ai_roles_id) {
                return AiRole::find($course->ai_roles_id);
            }
        }
        
        if ($planId) {
            $plan = TeachingPlan::find($planId);
            if ($plan && $plan->ai_roles_id) {
                return AiRole::find($plan->ai_roles_id);
            }
        }
        
        // 获取用户默认角色
        return AiRole::where('user_id', $user->id)
            ->where('is_default', 1)
            ->find();
    }

    /**
     * 记录得分详情
     */
    protected function recordScore(User $user, LearningRecord $record, TeachingPlanElement $element, array $evaluation, string $content, ?int $messageId = null): ScoreDetail
    {
        $scoreDetail = new ScoreDetail();
        $scoreDetail->user_id = $user->id;
        $scoreDetail->learning_record_id = $record->id;
        $scoreDetail->element_id = $element->id;
        $scoreDetail->message_id = $messageId; // 新增消息ID字段
        $scoreDetail->question_score = $element->score;
        $scoreDetail->passing_score = $element->passing_score;
        $scoreDetail->achieved_score = $evaluation['score'];
        $scoreDetail->score_description = $evaluation['analysis'];
        $scoreDetail->answer_content = $content;
        $scoreDetail->is_passed = $evaluation['passed'] ? 1 : 0;
        $scoreDetail->answer_time = time();
        $scoreDetail->save();

        // 更新总得分
        $record->achieved_score += $evaluation['score'];
        $record->last_study_at = time();
        $record->save();

        return $scoreDetail;
    }

    /**
     * 判断是否继续下一个元素
     */
    protected function shouldContinueToNext(bool $isPassed, string $learningMode): bool
    {
        if ($learningMode === 'testing') {
            return true; // 测验模式总是继续
        }
        
        return $isPassed; // 培训模式需要通过才继续
    }

    /**
     * 获取下一个教案元素
     */
    protected function getNextElement(TeachingPlanElement $currentElement): ?TeachingPlanElement
    {
        return TeachingPlanElement::where('plan_id', $currentElement->plan_id)
            ->where('sort_order', '>', $currentElement->sort_order)
            ->order('sort_order', 'asc')
            ->find();
    }

    /**
     * 更新学习进度
     */
    protected function updateLearningProgress(LearningRecord $record, int $nextElementId): void
    {
        $record->current_element_id = $nextElementId;
        $record->last_study_at = time();
        $record->save();
    }

    /**
     * 创建AI回复消息
     */
    protected function createAiResponseMessage(User $user, int $sessionId, TeachingPlanElement $element, ?AiRole $aiRole, string $learningMode, ?array $evaluation = null): ChatMessage
    {
        // 构建系统提示
        $systemPrompt = $this->buildTeachingPrompt($element, $aiRole, $learningMode, $evaluation);
        
        $aiMessage = new ChatMessage();
        $aiMessage->session_id = $sessionId;
        $aiMessage->user_id = $user->id;
        $aiMessage->message_type = ChatMessage::TYPE_TEXT;
        $aiMessage->content = ''; // 内容将通过流式响应填充
        $aiMessage->is_ai = true;
        $aiMessage->save();

        return $aiMessage;
    }

    /**
     * 构建教学提示
     */
    protected function buildTeachingPrompt(TeachingPlanElement $element, ?AiRole $aiRole, string $learningMode, ?array $evaluation = null): string
    {
        $rolePrompt = $aiRole ? $aiRole->description : '你是一位专业的教学助手';
        
        if ($element->type === TeachingPlanElement::TYPE_LECTURE) {
            return "{$rolePrompt}。请向学生讲解以下知识点：\n\n" .
                   "知识点：{$element->point}\n" .
                   "内容：{$element->content}\n\n" .
                   ($learningMode === 'training' ? 
                    "请用通俗易懂的方式进行讲解，确保学生能够理解。" : 
                    "请简洁明了地进行讲解。");
        } else {
            $prompt = "{$rolePrompt}。" . ($evaluation ? 
                "学生刚刚回答了问题，评分结果：{$evaluation['score']}分（满分{$element->score}分），" .
                ($evaluation['passed'] ? '已通过' : '未通过') . "。分析：{$evaluation['analysis']}\n\n" :
                "请向学生提出以下问题：\n\n");
            
            $prompt .= "问题：{$element->content}\n";
            
            if ($learningMode === 'training') {
                $prompt .= $evaluation && !$evaluation['passed'] ? 
                    "\n由于学生未通过，请给出详细的解释和引导，帮助学生理解正确答案。" :
                    "\n如果学生回答不正确，请耐心引导并给出提示。";
            } else {
                $prompt .= "\n请客观评估学生的回答，给出建设性的反馈。";
            }
            
            return $prompt;
        }
    }

    /**
     * 计算学习进度
     */
    protected function calculateProgress(LearningRecord $record): array
    {
        $plan = TeachingPlan::find($record->current_plan_id);
        if (!$plan) {
            return [
                'current_element_id' => $record->current_element_id,
                'total_elements' => 0,
                'completed_elements' => 0,
                'progress_rate' => 0,
                'current_plan_id' => $record->current_plan_id
            ];
        }

        $totalElements = $plan->total_elements;
        $completedElements = ScoreDetail::where('learning_record_id', $record->id)
            ->where('is_passed', 1)
            ->count('DISTINCT element_id');

        $progressRate = $totalElements > 0 ? ($completedElements / $totalElements) * 100 : 0;
        
        // 更新记录中的进度
        $record->progress_rate = $progressRate;
        $record->save();

        return [
            'current_element_id' => $record->current_element_id,
            'total_elements' => $totalElements,
            'completed_elements' => $completedElements,
            'progress_rate' => round($progressRate, 2),
            'current_plan_id' => $record->current_plan_id
        ];
    }

    /**
     * 查找现有学习记录
     */
    protected function findExistingLearningRecord(User $user, ?int $courseId, ?int $teachingPlanId): ?array
    {
        return Db::table('learning_records')
            ->alias('lr')
            ->join('chat_sessions cs', 'cs.learning_records_id = lr.id')
            ->where('lr.user_id', $user->id)
            ->where(function ($query) use ($courseId, $teachingPlanId) {
                if ($courseId) {
                    $query->where('lr.course_id', $courseId);
                } else {
                    $query->where('lr.teaching_plan_id', $teachingPlanId);
                }
            })
            ->where('lr.status', LearningRecord::STATUS_IN_PROGRESS)
            ->where('lr.delete_time', null)
            ->where('cs.delete_time', null)
            ->field([
                'lr.id as learning_records_id',
                'cs.id as session_id'
            ])
            ->find();
    }

    /**
     * 创建新的学习会话
     */
    protected function createNewLearningSession(User $user, ?int $courseId, ?int $teachingPlanId, ?int $elementId, string $learningMode): array
    {
        // 创建学习记录
        $learningRecord = new LearningRecord();
        $learningRecord->user_id = $user->id;
        $learningRecord->course_id = $courseId;
        $learningRecord->teaching_plan_id = $teachingPlanId;
        $learningRecord->current_plan_id = $teachingPlanId;
        $learningRecord->learning_type = $learningMode === 'testing' ? LearningRecord::TYPE_EXAM : LearningRecord::TYPE_REVIEW;
        $learningRecord->status = LearningRecord::STATUS_IN_PROGRESS;
        $learningRecord->last_study_at = time();
        $learningRecord->save();

        // 创建会话
        $session = $this->chatService->createSession($user, [
            'title' => $courseId ? '课程学习会话' : '教案学习会话',
            'session_type' => 4, // 学习会话
            'learning_records_id' => $learningRecord->id
        ]);

        $firstElementId = $elementId ?: $this->getFirstElementId($learningRecord);
        if ($firstElementId) {
            $learningRecord->current_element_id = $firstElementId;
            $learningRecord->save();
        }

        return [
            'session_id' => $session->id,
            'learning_record_id' => $learningRecord->id,
            'first_element_id' => $firstElementId,
            'total_elements' => $this->getTotalElements($learningRecord),
            'teaching_plan' => $this->getTeachingPlanInfo($teachingPlanId),
            'course' => $courseId ? $this->getCourseInfo($courseId) : null
        ];
    }

    /**
     * 获取第一个教案元素ID
     */
    protected function getFirstElementId(LearningRecord $record): ?int
    {
        $planId = $record->current_plan_id ?: $record->teaching_plan_id;
        $element = TeachingPlanElement::where('plan_id', $planId)
            ->order('sort_order', 'asc')
            ->find();
        return $element ? $element->id : null;
    }

    /**
     * 获取教案元素总数
     */
    protected function getTotalElements(LearningRecord $record): int
    {
        $planId = $record->current_plan_id ?: $record->teaching_plan_id;
        $plan = TeachingPlan::find($planId);
        return $plan ? $plan->total_elements : 0;
    }

    /**
     * 获取教案信息
     */
    protected function getTeachingPlanInfo(?int $planId): ?array
    {
        if (!$planId) return null;
        
        $plan = TeachingPlan::find($planId);
        return $plan ? [
            'id' => $plan->id,
            'title' => $plan->title,
            'description' => $plan->description
        ] : null;
    }

    /**
     * 获取课程信息
     */
    protected function getCourseInfo(?int $courseId): ?array
    {
        if (!$courseId) return null;
        
        $course = CourseOutline::find($courseId);
        return $course ? [
            'id' => $course->id,
            'title' => $course->title,
            'description' => $course->description
        ] : null;
    }

    /**
     * 获取最近得分记录
     */
    protected function getRecentScores(int $learningRecordId): array
    {
        return ScoreDetail::where('learning_record_id', $learningRecordId)
            ->order('created_at', 'desc')
            ->limit(10)
            ->select()
            ->map(function($score) {
                return [
                    'element_id' => $score->element_id,
                    'score' => $score->achieved_score,
                    'passed' => $score->is_passed == 1,
                    'answer_time' => date('Y-m-d H:i:s', $score->answer_time)
                ];
            })
            ->toArray();
    }

    /**
     * 获取状态文本
     */
    protected function getStatusText(int $status): string
    {
        switch ($status) {
            case LearningRecord::STATUS_IN_PROGRESS:
                return '进行中';
            case LearningRecord::STATUS_COMPLETED:
                return '已完成';
            case LearningRecord::STATUS_INTERRUPTED:
                return '已中断';
            default:
                return '未知状态';
        }
    }
}